package gen

import (
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"strings"
)

type Modules struct {
	Modules []Module `xml:"module"`
}

type Module struct {
	IsGenMapper     bool   `xml:"mapper,attr"`
	IsGenDomain     bool   `xml:"domain,attr"`
	IsGenDao        bool   `xml:"dao,attr"`
	IsGenService    bool   `xml:"service,attr"`
	IsGenController bool   `xml:"controller,attr"`
	Project         string `xml:"project"`
	Name            string `xml:"name"`
	Gen             bool   `xml:"gen"`
	CreatePackage   bool   `xml:"createPackage"`
	Tables          string `xml:"tables"`
	Cloums          map[string][]ClouMsg
	SProject        Porject
}

func ModuleInit(projects Porjects, filePath string) []Module {
	fmt.Println("初始化模块...")
	content, err := ioutil.ReadFile(ConfDir + filePath)
	var config = Modules{}
	if err != nil {
		fmt.Println("读取模块配置出错:", err.Error())
		return nil
	}
	err = xml.Unmarshal(content, &config)
	if err != nil {
		fmt.Println("解析数据库配置错误:", err.Error())
		return nil
	}
	var genModule = make([]Module, 0, 1)
	fmt.Println("初始化模块完成，筛选要生成的模块")
	for _, project := range projects.Projects {
		if project.Gen {
			for _, module := range config.Modules {
				if module.Gen && module.Project == project.Name {
					var mod = module
					var tables = strings.Split(mod.Tables, ",")
					mod.Cloums = make(map[string][]ClouMsg)
					mod.SProject = project
					for _, table := range tables {
						mod.Cloums[table] = Query(table)
					}
					genModule = append(genModule, mod)
				}
			}
		}
	}
	return genModule
}
